import { Component, OnInit } from '@angular/core';
import { AxiosService } from '../../axios.service';
import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { DatePipe } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-yanshou',
  templateUrl: './yanshou.component.html',
  styleUrls: ['./yanshou.component.scss'],
  providers: [DatePipe],

})

export class YanshouComponent implements OnInit {
  isVisible;
  isOkLoading;
  filterEsData;
  item;
  add19code;//编辑19码
  isOkLoading19Code;

  addEngineer;//添加工程师
  isOkLoadingEngineer;

  fileInfom;//显示工单对应的文件信息
  isOkLoadingfileInfom;

  isFileVisible;
  isFileOkLoading;

  public auditRemark: string = "";//审核备注
  public auditRemark2: string = "";//审核备注

  addAudit;//主管审核
  isOkLoadingAudit;
  // public auditRemark = [];
  fileStatus;//主管审核状态
  fileStatus0;//未审核
  fileStatus1;//已审核
  fileStatus2;//被退回

  clickName;//点击人名传参
  designDate;//设计期限
  first: any;//首个19码
  tail: any;//结尾19码
  newCode19;//提示已存在的19码
  show19code;//是否显示提示信息
  selectName;//选中的工程师
  objectKeys = Object.keys;
  objectValues = Object.values;
  splitJudge: string = ',';

  public isChoose: Boolean = true;//指派工程师复选框
  EngData;
  estimate_time;//预计时间

  //所有工单数据
  public tempData = [];

  //所有工件数据
  public workData = [];

  //工程师数组
  public engineerData;
  public engineerDataCheckBoox = []; // 创建和engineerData个数一致的数组
  public engPerson = []; // 指派工程师
  //意同tempData
  dataTemp;

  // 接收要修改的数据
  updateData;

  public unionorder: any;//"WAKS20200304ZCH002",
  public newValue: any;//"新值"
  name;//"表中栏位名称",
  id;//文件信息id

  selectData = [];
  selectName2 = [];//存放选取的两位工程师
  newArr = []; //定义空的新数组

  code19Data = [];//存放19码的数组

  public listOfData = [];//工单文件区数据

  fileName;//文件名
  filePath;//文件路径
  fileData;//得到的base64格式数据

  public workName;//下载时需补齐的文件路径
  public link;//下载链接
  listfd=[];

  checkBoxStatus = [
    { 'title': '進行中', 'checked': true, 'select': 0 },
    { 'title': '已完成', 'checked': false, 'select': 1 }
    // { 'title': '已取消', 'checked': true, 'select': 2 },
  ];

  infom = [
    { 'value': 'ok' },
    { 'value': '格式錯誤' },
    { 'value': '時間錯誤' },
    { 'value': '標註有問題' },
    { 'value': '信息錯誤' },
    { 'value': '信息有遺漏' },
    { 'value': '信息不完整' },
    { 'value': '請補充信息' }
  ];
  checkable;//备注信息
  selectedTags: string[] = [];


  constructor(
    public axios: AxiosService,
    private storage: LocalStorageService,
    private datePipe: DatePipe,
    private router: Router
  ) { }

  ngOnInit(): void {
    //获取全部数据
    this.getDoingData();
    // this.addEngineerData()
  }
  //查询进行中工单信息
  getDoingData() {
    this.selectData = [];
    this.axios.axiosPost('QueryUnionOrderByStatusStage', { "stage": 6, "stageValue": 1, "status": 6 })
      .then((data) => {
        if (data) {
          this.listfd=[];
          this.tempData = data['order'];
          this.dataTemp = this.tempData;
          console.log(this.dataTemp)
          const addData = this.dataTemp.filter(res => res['status'] === 0);
          this.selectData = this.selectData.concat(addData);
          for (var i = 0; i < this.tempData.length; i++) {
            // 实际时间栏位把秒转为小时
            this.tempData[i].total_time = Number(this.tempData[i].total_time) / 3600;
            if (this.tempData[i].total_time > 0.00) {
              this.tempData[i].total_time = Math.floor((this.tempData[i].total_time + 0.01) * 100) / 100;
            }
            this.listfd.push(new Array)
          }
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  //查询工单状态
  doingForm(data) {
    // 选中
    if (!data.checked) {
      const addData = this.dataTemp.filter(res => res['status'] === data.select);
      this.selectData = this.selectData.concat(addData);
      console.log(this.selectData)
    }
    // 未选中
    if (data.checked) {
      const deleteData = this.selectData.filter(res => res['status'] === data.select);
      this.selectData = this.selectData.filter(item => !deleteData.some(ele => ele['status'] === item['status']));
      console.log(this.selectData)
    }
  }

  //查询工件信息
  collapse(item, key) {
    console.log(key)
    console.log(item.expand);
    console.log(this.selectData)
    this.axios.axiosPost('QueryWorkOrder', { 'unionorder': this.selectData[key].union_order, "status": 6 })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok' && data['order'].length > 0) {
          this.listfd[key]=new Array;
          this.workData[key] = data['order'];
          for(var i =0;i<this.workData[key].lenght;i++){
            this.listfd[key].push(new Array)
          }
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  //取消工單
  handleCancel() {
    this.isVisible = false;
    this.auditRemark2 = "";
  }
  //确定取消按钮
  handleOk() {
    // debugger
    if (this.auditRemark2) {
      this.isOkLoading = true;
      this.isVisible = false;
      this.isOkLoading = false;
      this.axios.axiosPost('UpdateUnionOrder2', { 'unionorder': this.updateData.union_order, 'name1': 'status', 'newValue1': '2', 'name2': 'cancel_remark', 'newValue2': this.auditRemark2, })
        .then((data) => {
          console.log(data)
          // debugger
          if (data['result'] === 'ok') {
            this.getDoingData();
            // this.getAllData();
          }
        })
    } else {
      alert("未填寫刪除工單的原因")
    }
  }
  showModal(item) {
    this.isVisible = true;
    this.updateData = item;
  }

  //点击添加19码
  addCode19(item) {
    console.log(item)
    this.first = item.code19.split(',')[0];
    this.tail = item.code19.split(',')[1];
    this.add19code = true;
    this.updateData = item;
  }
  //确定添加19码
  add19CodeOk() {
    this.isOkLoading19Code = true;
    this.add19code = false;
    this.isOkLoading19Code = false;
    this.show19code = false;
    console.log(this.first);
    if (this.first === '' && this.tail === '') {
      alert("输入框不能都为空！")
    }
    let A = this.first.substr(0, 15);//first前15位
    let a = parseInt(this.first.substr(15, 4));//first后4位
    let B;
    let b;
    if (this.tail === '') {
      B = '';
      b = 0;
    } else {
      B = this.tail.substr(0, 15);
      b = parseInt(this.tail.substr(15, 4));
    }
    console.log(a, b)
    // 判断前15位是否一致
    if (A === B) {
      //首位19码必须小于末尾19码
      if (a < b) {
        this.axios.axiosPost('UpdateUnionOrder', { 'unionorder': this.updateData.union_order, 'name': 'code19', 'newValue': this.first + ',' + this.tail })
          .then((data) => {
            console.log(data)
            if (data['result'] === 'ok') {
              this.getDoingData();
              this.add19code = false;
              this.show19code = false;
            } else if (data['result'] === 'error') {
              this.show19code = true;
              this.newCode19 = data['code19'];
              this.add19code = true;
            }
          })
      } else {
        this.add19code = true;
        alert("末尾19码不能小于首位19码")
      }
    } else {
      this.add19code = true;
      alert("输入的首尾19码前15位不一致")
    }
  }

  //取消添加19码
  CancelAdd19Code() {
    this.add19code = false;
  }

  //取消指派工程师
  CancelAddEngineer() {
    this.addEngineer = false;
  }
  //确定指派工程师
  AddEngineerOK() {
    this.designDate = this.datePipe.transform(this.designDate, 'yyyy-MM-dd');
    if (this.designDate === null) {
      this.designDate = '';
    }
    console.log(this.designDate, this.estimate_time);
    console.log(this.selectName2)
    this.axios.axiosPost('UpdateUnionOrder2', {
      'unionorder': this.clickName.union_order,
      'name1': 'engineer', 'newValue1': this.selectName2,
      'name2': 'design_end_date', 'newValue2': this.designDate,
      'name3': 'estimate_time', 'newValue3': this.estimate_time
    })
      .then((data) => {
        this.CancelAddEngineer();
        console.log(data)
        if (data['result'] === 'ok') {
          this.getDoingData();
        }
      })
  }
  //点击工程师或指派按钮
  addEngine(item) {
    console.log('点击的姓名 \n', item);


    this.clickName = item;

    if (item.engineer !== '' || item.engineer) {
      this.selectName2 = item.engineer.split(',');
    } else {
      this.selectName2 = [];
    }


    this.designDate = item.design_end_date;
    this.estimate_time = item.estimate_time;

    // this.selectName2 = [];
    this.addEngineer = true;
    this.axios.axiosPost('QueryUser', { 'level': 1, })
      .then((data) => {
        console.log(data, "我在这啊啊 啊啊 啊啊啊啊啊啊啊啊")
        if (data['result'] === 'ok') {
          this.engineerData = data['order'];
          const arr = [];
          this.engineerDataCheckBoox = [];
          for (let k = 0; k < this.engineerData.length; k++) {
            arr.push(this.engineerData[k].name)
            console.log(this.engineerData[k].name)
            this.engineerDataCheckBoox.push(false);

          }

          // 弹出以后 显示哪些人被选中
          console.log(this.selectName2)
          if (this.selectName2.length > 0) {
            // debugger
            for (let i = 0; i < this.selectName2.length; i++) {
              const key = arr.indexOf(this.selectName2[i]);
              console.log(key)
              if (key > -1) {
                this.engineerDataCheckBoox.splice(key, 1, true)
                console.log(this.engineerDataCheckBoox)
              }
            }
          } else {
            console.log(this.engineerData.length)
            for (let k = 0; k < this.engineerData.length; k++) {
              this.engineerDataCheckBoox.push(false)
            }
          }
          console.log('#@@@@@@@@@@@@ \n', this.engineerDataCheckBoox)
        }
      })
  }
  //选择工程师
  selEngineer(data, key) {
    // console.log("--------------\n", data,this.engineerDataCheckBoox, key)
    // 改变选择项的状态
    const status = this.engineerDataCheckBoox[key];
    if (status) {
      this.engineerDataCheckBoox.splice(key, 1, false);
    } else {
      this.engineerDataCheckBoox.splice(key, 1, true);
    }
    console.log(this.engineerDataCheckBoox)
    console.log(key)
    if (this.engineerDataCheckBoox[key]) {
      this.selectName2.push(this.engineerData[key].name);
    } else {
      const index = this.selectName2.indexOf(this.engineerData[key].name)
      if (this.selectName2.indexOf(this.engineerData[key].name > -1)) { // 如果selectName2包含要去掉的数据
        console.log('索引 === \n', index)
        this.selectName2.splice(index, 1)
      }
    }
    console.log('################### \n', this.selectName2)
  }
  //定义函数：判断元素是否在数组中
  unique(arr: any) {
    var array = [];
    for (var i = 0; i < arr.length; i++) {
      if (array.indexOf(arr[i]) === -1) {
        array.push(arr[i])
      }
    }
    return array;
  }

  currentPageDataChange(qqq) {

  }

  //点击图标显示此工单的文件信息
  downLoad(infom) {
    // debugger
    this.fileInfom = true;
    console.log(infom)
    this.updateData = infom;
    this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.updateData.union_order, 'workorder': this.updateData.name })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          this.listOfData = data['files'];
          this.workName = this.updateData.union_order;
          console.log(this.listOfData, this.workName)

        }
      })
  }

  CancelShow() {
    this.fileInfom = false;
  }

  ShowOK() {
    this.isOkLoadingfileInfom = true;
    this.fileInfom = false;
    this.isOkLoadingfileInfom = false;
  }

  //主管审核
  ClickAudit(data, key) {

    this.addAudit = true;
    this.fileStatus = data.file_status;
    this.id = data.id;
    this.filePath = data.file_path;
    console.log('=============== \n', data, key, this.id);
  }

  //取消审核
  CancelAudit() {
    this.addAudit = false;
  }

  //确定审核按钮
  auditOk() {
    this.isOkLoadingAudit = true;
    this.addAudit = false;
    this.isOkLoadingAudit = false;
    // debugger
    let index = this.auditRemark.indexOf('ok');//判断是否含有此值
    if (index === 0) {
      this.fileStatus = 1;//审核通过
    } else {
      this.fileStatus = 2;//已退回
    }
    console.log(this.id)
    this.axios.axiosPost('UpdateWorkFile', {
      'id': this.id,
      'name': 'file_status', 'newValue': this.fileStatus,
      'name2': 'remark', 'newValue2': this.auditRemark
    })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          // debugger
          this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.updateData.union_order, 'workorder': this.updateData.name })
            .then((data) => {
              console.log(data)
              if (data['result'] === 'ok') {
                this.listOfData = data['files'];
                this.workName = this.updateData.union_order;
                console.log(this.listOfData, this.workName)
              }
            })
          if (this.fileStatus === 1) {
            this.axios.axiosPost('ParseBOMFile', { 'filepath': this.filePath, 'action': 'check' })
              .then((data) => {
                console.log(data)
                if (data['result'] === 'ok') {
                  // this.QueryWorkOrder(key);
                }
              })
          }
        }
      })
  }
  //填写审核备注
  handleChange(checked: boolean, tag: string): void {
    // this.selectedTags = [];
    // if(checked) {
    //   this.selectedTags.push(tag);
    // } else {
    //   this.selectedTags = this.selectedTags.filter(t => t !== tag);
    // }
    //   console.log(this.selectedTags);
    // this.auditRemark = this.selectedTags[0]['value'];//赋值
    var msg = tag['value'];
    if (this.auditRemark.length > 0) {
      var index = this.auditRemark.indexOf(msg);
      if (index >= 0) {
        var temp = this.auditRemark.split(msg).join('');
        while (temp.length > 0 && temp[0] == ' ') {
          temp = temp.substr(1);
        }
        while (temp.length > 0 && temp[temp.length - 1] == ' ') {
          temp = temp.substr(0, temp.length - 1);
        }
        this.auditRemark = temp.replace('  ', ' ');
      }
      else {
        this.auditRemark += ' ' + msg;
      }
    }
    else {
      this.auditRemark = msg;
    }
  }


  //下载文件
  downLoadFile(data) {
    console.log(data)
    debugger
    this.fileName = data.file_name;
    this.link = this.axios.domainTest1 + this.workName + '/' + this.fileName;
    console.log(this.fileName, this.link)
  }

  handleFileCancel() {
    this.isFileVisible = false;
  }

  //删除文件信息
  showDelFile(data) {
    this.isFileVisible = true;
    console.log(data)
    this.id = data.id;
  }

  delFileOk() {
    this.isFileOkLoading = true;
    this.isFileVisible = false;
    this.isFileOkLoading = false;
    this.axios.axiosPost('DeleteWorkFile', { 'id': this.id })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          let listData = this.listOfData.filter(res => res['id'] !== this.id)
          this.listOfData = listData;
        }
      })
  }
  QueryWorkOrder2(a,b,c) {
    console.log("触发", a)
    this.axios.axiosPost("QueryCncDataSubOrder", { "unionorder": a.unionorder, "workorder": a.sheet_order,status:6}).then((data) => {
      console.log(data);
      if (data["result"] == "ok") {
        this.listfd[b][c] = data["order"];
      }
    })
  }
}
